import { ref } from 'vue'
import store from '@/store'
import router from '@/router'
import { defineStore } from 'pinia'
import { constantRoutes, dynamicRoutes } from '@/router'
import { flatMultiLevelRoutes } from '@/router/helper'
import routeSettings from '@/config/route'
import { $t } from '@/languages/index'

const Layouts = () => import('@/layouts/index.vue')
const modules = import.meta.glob('@/views/**/*.vue')

const mockDynamicRoutes = [
  {
    path: '/permission',
    component: 'Layouts',
    redirect: '/permission/pageAuth',
    name: 'Permission',
    meta: {
      title: 'permission',
      i18nKey: 'permission',
      elIcon: 'Lock',
      roles: ['admin', 'editor'],
      alwaysShow: true
    },
    children: [
      {
        path: 'pageAuth',
        component: 'permission/pageAuth/index',
        name: 'PagePermission',
        meta: {
          title: 'pagePermission',
          i18nKey: 'pagePermission',
          roles: ['admin']
        }
      },
      {
        path: 'directive',
        component: 'permission/directive/index',
        name: 'DirectivePermission',
        meta: {
          title: 'directivePermission',
          i18nKey: 'directivePermission'
        }
      }
    ]
  },
  {
    path: '/purchases',
    component: 'Layouts',
    redirect: '/purchases/requisitions',
    name: 'Purchases',
    meta: { title: 'purchases', i18nKey: 'purchases', elIcon: 'Memo' },
    children: [
      {
        path: 'requisitions',
        name: 'Requisitions',
        component: 'purchases/requisitions/index',
        meta: { title: 'requisitions', i18nKey: 'requisitions' }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: 'purchases/orders/index',
        meta: { title: 'orders', i18nKey: 'orders' }
      }
    ]
  },
  {
    path: '/sales',
    component: 'Layouts',
    redirect: '/sales/quotations',
    name: 'Sales',
    meta: { title: 'sales', i18nKey: 'sales', elIcon: 'Sell' },
    children: [
      {
        path: 'quotations',
        name: 'SalesQuotations',
        component: 'sales/quotations/index',
        meta: { title: 'salesQuotations', i18nKey: 'salesQuotations', keepAlive: true }
      },
      {
        path: 'orders',
        name: 'SalesOrders',
        component: 'sales/orders/index',
        meta: { title: 'salesOrders', i18nKey: 'salesOrders', keepAlive: true }
      }
    ]
  }
]

//根据角色判断是否有权限
const hasPermission = (roles, route) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some(role => routeRoles.includes(role)) : true
}
//根据角色过滤路由
const filterDynamicRoutes = (routes, roles) => {
  const res = []
  routes.forEach(route => {
    const tempRoute = { ...route }
    if (hasPermission(roles, tempRoute)) {
      if (tempRoute.children) {
        tempRoute.children = filterDynamicRoutes(tempRoute.children, roles)
      }
      res.push(tempRoute)
    }
  })
  return res
}

/** 根据目录生成路由 */
function generateRouters(routes) {
  return routes.map(route => {
    if (route.component) {
      if (route.component === 'Layouts') {
        route.component = Layouts
      } else {
        route.component = loadView(route.component)
      }
    }
    // 如果存在子路由，递归调用转换函数
    if (route.children && route.children.length > 0) {
      route.children = generateRouters(route.children)
    }
    return route
  })
}

const loadView = view => {
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

export const usePermissionStore = defineStore('permission', () => {
  // 可访问的路由(动态+静态)
  const routes = ref([])
  //有访问权限的动态路由
  const addRoutes = ref([])
  //返回的初始路由
  const initRoutes = ref([])

  /** 获取路由 */
  const getRouters = async () => {
    return new Promise(resolve => {
      const data = {
        routes: mockDynamicRoutes
      }
      initRoutes.value = data.routes
      setTimeout(() => {
        resolve(data)
      }, 500)
    })
  }

  /** 根据角色生成可访问的 Routes（可访问的路由 = 常驻路由 + 有访问权限的动态路由） */
  const setRoutes = roles => {
    // const accessedRoutes = filterDynamicRoutes(dynamicRoutes, roles)
    // console.log(accessedRoutes, 'accessedRoutes')
    // _set(accessedRoutes)
  }

  /**（没有根据角色过滤掉的） 所有路由 = 所有常驻路由 + 所有远程动态路由 */
  const setAllRoutes = () => {
    // 匹配本地文件目录路由
    const routers = generateRouters(initRoutes.value)
    _set(routers)
  }

  // 内部方法
  const _set = accessedRoutes => {
    // 动态静态合并
    const allRoutes = constantRoutes.concat(accessedRoutes)
    const allNewRoutes = setRouterTitle(allRoutes, $t)
    routes.value = allNewRoutes
    addRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes
    //添加到路由表中
    addRoutes.value.forEach(route => router.addRoute(route))
  }

  /**设置路由title */
  const setRouterTitle = (newRoute, t) => {
    return newRoute.map(route => {
      const tmp = { ...route }
      // 翻译路由标题
      if (tmp.meta?.title && tmp.meta?.i18nKey) {
        const transTitle = 'common.router.' + tmp.meta?.i18nKey
        tmp.meta.title = t(transTitle)
      }
      if (tmp.children && tmp.children.length > 0) {
        tmp.children = setRouterTitle(tmp.children, t)
      }
      return tmp
    })
  }

  return { routes, addRoutes, setRoutes, setAllRoutes, getRouters, setRouterTitle }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
